package io.gitee.kotle.android.utils

import com.google.gson.GsonBuilder
import com.google.gson.JsonParser
import com.google.gson.JsonElement
import java.util.TreeMap
import java.util.Comparator


/**
 *
 * 描述：
 *
 * 创建人：jiale.wei
 * 创建时间：2022/1/13 9:05 上午
 *
 */

/**
 * 定义比较规则
 */

private val defaultComparatorStr = Comparator<String> { s1, s2 -> s1.compareTo(s2) }

/**
 * 用于排序的gson对象
 */
private val gson = GsonBuilder().setPrettyPrinting().create()

fun String.sortByGson(comparator: Comparator<String> = defaultComparatorStr): String {
    val jsonElement = JsonParser.parseString(this)
    sort(jsonElement, comparator)
    return gson.toJson(jsonElement)
}


/**
 * 排序
 */
private fun sort(jsonElement: JsonElement, comparator: Comparator<String>) {
    if (jsonElement.isJsonNull || jsonElement.isJsonPrimitive) {
        return
    }
    if (jsonElement.isJsonArray) {
        jsonElement.asJsonArray.forEach {
            sort(it, comparator)
        }
        return
    }
    if (jsonElement.isJsonObject) {
        val tm: MutableMap<String, JsonElement> = TreeMap(comparator)
        for ((key, value) in jsonElement.asJsonObject.entrySet()) {
            tm[key] = value
        }
        for ((key, value) in tm) {
            jsonElement.asJsonObject.remove(key)
            jsonElement.asJsonObject.add(key, value)
            sort(value, comparator)
        }
    }
}